package com.ifacebox.face.track.ui;

import com.ifacebox.face.track.model.FacePage;
import com.ifacebox.face.track.utils.DebugUtils;
import com.ifacebox.face.track.utils.ThreadUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.Objects;

/**
 * @author znn
 */
public class FacePageToolBar extends JToolBar implements Runnable, ActionListener, ItemListener {
    private static final ImageIcon PAGE_HOME_ICON = new ImageIcon(Objects.requireNonNull(FacePageToolBar.class.getResource("/page_home.png")));
    private static final ImageIcon PAGE_LAST_ICON = new ImageIcon(Objects.requireNonNull(FacePageToolBar.class.getResource("/page_last.png")));
    private static final ImageIcon PAGE_NEXT_ICON = new ImageIcon(Objects.requireNonNull(FacePageToolBar.class.getResource("/page_next.png")));
    private static final ImageIcon PAGE_END_ICON = new ImageIcon(Objects.requireNonNull(FacePageToolBar.class.getResource("/page_end.png")));
    private static final String PAGE_INFO_FORMAT = "共%d条 当前第%d/%d页";
    private final JLabel pageInfo;
    private final JButton pageHome, pageLast, pageNext, pageEnd;
    private final FacePagePicker facePagePicker;
    private int totalSize, pageIndex, pageSize, pageCount, fromIndex, toIndex;
    private final Callback callback;

    public FacePageToolBar(Callback callback) {
        this.callback = callback;
        super.setFloatable(false);
        super.setLayout(new FlowLayout());
        super.add(this.pageInfo = new JLabel(String.format(PAGE_INFO_FORMAT, 0, 0, 0)));
        super.add(this.pageHome = new JButton(PAGE_HOME_ICON) {{
            this.addActionListener(FacePageToolBar.this);
        }});
        super.add(this.pageLast = new JButton(PAGE_LAST_ICON) {{
            this.addActionListener(FacePageToolBar.this);
        }});
        super.add(this.pageNext = new JButton(PAGE_NEXT_ICON) {{
            this.addActionListener(FacePageToolBar.this);
        }});
        super.add(this.pageEnd = new JButton(PAGE_END_ICON) {{
            this.addActionListener(FacePageToolBar.this);
        }});
        super.add(this.facePagePicker = new FacePagePicker() {{
            this.addItemListener(FacePageToolBar.this);
        }});
    }

    public void setTotalSize(int totalSize) {
        this.totalSize = totalSize;
    }

    public void refresh() {
        if (this.totalSize <= 0) {
            this.pageSize = 0;
        } else {
            this.pageSize = this.facePagePicker.getSelectedPage().getSize();
        }
        if (this.pageSize <= 0) {
            this.pageCount = 0;
        } else {
            if (this.totalSize % this.pageSize > 0) {
                this.pageCount = this.totalSize / this.pageSize + 1;
            } else {
                this.pageCount = this.totalSize / this.pageSize;
            }
        }
        if (this.pageIndex * this.pageSize >= this.totalSize) {
            this.pageIndex = 0;
        }
        this.fromIndex = Math.min(this.totalSize, this.pageIndex * this.pageSize);
        this.toIndex = Math.min(this.totalSize, fromIndex + this.pageSize);
        this.pageInfo.setText(String.format(PAGE_INFO_FORMAT, this.totalSize, Math.min(this.totalSize, this.pageIndex + 1), this.pageCount));
        DebugUtils.debug("共%d条记录\t每页条%d记录\t当前第%d/%d页\t显示第%d-%d条记录"
                , this.totalSize, this.pageSize, Math.min(this.totalSize, this.pageIndex + 1), this.pageCount, this.fromIndex, this.toIndex);
        this.pageHome.setEnabled(false);
        this.pageLast.setEnabled(false);
        this.pageNext.setEnabled(false);
        this.pageEnd.setEnabled(false);
        this.facePagePicker.setEnabled(false);
        ThreadUtils.runThread(this);
    }

    @Override
    public void run() {
        try {
            this.callback.call(this.fromIndex, this.toIndex);
        } finally {
            SwingUtilities.invokeLater(() -> {
                this.pageHome.setEnabled(Math.min(this.totalSize, this.pageIndex + 1) > 1);
                this.pageLast.setEnabled(Math.min(this.totalSize, this.pageIndex + 1) > 1);
                this.pageNext.setEnabled(Math.min(this.totalSize, this.pageIndex + 1) < this.pageCount);
                this.pageEnd.setEnabled(Math.min(this.totalSize, this.pageIndex + 1) < this.pageCount);
                this.facePagePicker.setEnabled(true);
            });
        }
    }

    @Override
    public void itemStateChanged(ItemEvent e) {
        FacePage facePage = this.facePagePicker.getSelectedPage();
        if (this.pageSize != facePage.getSize()) {
            this.pageSize = facePage.getSize();
            this.refresh();
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == this.pageHome) {
            this.pageIndex = 0;
        }
        if (e.getSource() == this.pageLast) {
            this.pageIndex = Math.max(this.pageIndex - 1, 0);
        }
        if (e.getSource() == this.pageNext) {
            if (this.pageIndex + 1 >= this.pageCount) {
                this.pageIndex = Math.max(this.pageCount - 1, 0);
            } else {
                this.pageIndex = this.pageIndex + 1;
            }
        }
        if (e.getSource() == this.pageEnd) {
            this.pageIndex = Math.max(this.pageCount - 1, 0);
        }
        this.refresh();
    }

    interface Callback {
        /**
         * 分页回调
         *
         * @param fromIndex 数据范围低端（包括）
         * @param toIndex   数据范围高端（不包括）
         */
        void call(int fromIndex, int toIndex);
    }
}
